package rpc

import (
	"gitee.com/ameise84/e3dds/internal/log"
	"gitee.com/ameise84/e3dds/internal/message"
	"gitee.com/ameise84/e3net"
)

var _gService service

var rpcMsgPost func(*message.Msg)

func Start(opts *Options) (string, error) {
	return _gService.start(opts)
}

func Stop() {
	_gService.stop()
}

func SetRpcMsgPostFunc(f func(*message.Msg)) {
	rpcMsgPost = f
}

func TakeRpcConn(tag e3net.Tag, addr string) (*Conn, error) {
	ctx := takeRawContext()
	c := &Conn{
		raw: ctx,
	}
	_, err := _gService.agt.ConnectSync(tag, c.raw, addr)
	if err != nil {
		return nil, err
	}
	c.isActive.Store(true)
	log.GetLogger().Trace("take rpc conn").Object(c.raw).Println()
	return c, nil
}

func FreeRpcConn(c *Conn) {
	if c.isActive.CompareAndSwap(false, true) {
		log.GetLogger().Trace("free rpc conn success").Object(c.raw).Println()
		_ = c.raw.c.Close()
		freeRawContext(c.raw)
		c.raw = nil
	}
}
